#!/bin/bash
#
# Install server items
# - server group
# - developers group
# - server root directory 
# - copy over to server bin scripts
# - developers home (projects directory)
#

echo "================================================================="
echo "Install server ($SERVER_NAME): begin"

SERVER_HOME=/$SERVER_NAME
SERVER_USER=$SERVER_NAME
SERVER_GROUP=$SERVER_NAME
DEVELOPERS_GROUP=developers
DEVELOPERS_HOME=$SERVER_HOME/projects

source $COMMON_FUNC > /dev/null 2>&1
if [ $? -gt 0 ]; then
    echo "Error: This script requires common-func.bash"
    exit 1
fi

isRoot

# create server user/group
user_exists $SERVER_USER
if [ $? -eq 1 ]; 
then
    echo "Creating user $SERVER_USER"
    useradd -m $SERVER_USER
else
    echo "User $SERVER_USER already exists. Skipping user creation."
fi

# create developers group
group_exists $DEVELOPERS_GROUP
if [ $? -eq 1 ]; 
then
    echo "Creating group $DEVELOPERS_GROUP"
    groupadd $DEVELOPERS_GROUP
else
    echo "Group $DEVELOPERS_GROUP already exists. Skipping group creation."
fi

# create server home
if [ ! -d "$SERVER_HOME" ];
then
    echo "Creating $SERVER_HOME"
    mkdir -p $SERVER_HOME
else
    echo "$SERVER_HOME already exists. Skipping server directory creation."
fi

# create developers home
if [ ! -d "$DEVELOPERS_HOME" ];
then
    echo "Creating $DEVELOPERS_HOME"
    mkdir -p $DEVELOPERS_HOME
else
    echo "$DEVELOPERS_HOME already exists. Skipping server directory creation."
fi

# create server bin directory
if [ ! -d "$SERVER_HOME/bin" ];
then
    echo "Creating $SERVER_HOME/bin"
    mkdir -p $SERVER_HOME/bin
else
    echo "$SERVER_HOME already exists. Skipping server directory creation."
fi

if [ ! -d /projects ];
then
    echo "Creating root link (/projects) to $DEVELOPERS_HOME"
    ln -s $DEVELOPERS_HOME /projects
else
    echo "/projects already exists. Nothing to do."
fi

# copy over scripts
echo "Copying $BIN_DIR to $SERVER_HOME"
cp -R $BIN_DIR $SERVER_HOME/.

echo "Applying permissions to $SERVER_HOME"
chown -R $SERVER_USER:$SERVER_GROUP $SERVER_HOME
chmod -R 775 $SERVER_HOME

echo "Applying permissions to $DEVELOPERS_HOME"
chown -R :$DEVELOPERS_GROUP $DEVELOPERS_HOME
chmod -R 775 $DEVELOPERS_HOME

echo "Applying permissions to $SERVER_HOME/bin"
chmod -R 775 $SERVER_HOME/bin

backup /etc/skel/.bash_profile
if [ ! $? -eq 0 ];
then
    echo "Error: Encountered error during backup of /etc/skel/.bash_profile"
    pause '> Press [ENTER] to continue or [CTRL-C] to exit'
fi
cp $RESOURCES_DIR/system/bash_profile /etc/skel/.bash_profile

echo "Install server: done"
echo "================================================================="
